package com.homework.module6part3.controller;

//import com.homework.dao.domain.Message;
import com.homework.dao.domain.Goods;
import com.homework.dao.domain.Order;
import com.homework.dao.domain.OrderMessage;
import com.homework.dao.domain.User;
import com.homework.module6part3.service.GoodsService;
import com.homework.module6part3.service.OrderService;
import com.homework.module6part3.service.StockService;
import com.homework.util.ResultMsg;
import com.homework.util.ResultUtil;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Base64;
import org.apache.rocketmq.common.message.Message;

@Controller
public class SeckillController {
    @Autowired
    protected GoodsService goodsService;

    @Autowired
    protected StockService stockService;

    @Autowired
    protected OrderService orderService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @RequestMapping("/goods/{id}")
    public ModelAndView goodsDetail(@PathVariable int id) {
        ModelAndView modelAndView = new ModelAndView("detail");
        Goods goods = goodsService.getGoodsById(id);
        modelAndView.addObject("detail", goods);

        int start = 0; //秒杀未开始
        int now = (int)(System.currentTimeMillis() / 1000);
        if(now > goods.getStartTime() && now < goods.getEndTime()) {
           start = 1;  //秒杀进行中
        } else if(now >= goods.getEndTime()) {
            start = 2;  //秒杀已结束
        }
        modelAndView.addObject("start", start);

        return modelAndView;
    }

    @RequestMapping("/order/{id}")
    public ModelAndView goods(HttpServletRequest request, @PathVariable int id) {
        ModelAndView modelAndView = new ModelAndView("order");

        Order order = orderService.getOrder(id);
        modelAndView.addObject("order", order);
        return modelAndView;
    }

    @RequestMapping(value = "/doSeckill/{code}", method = {RequestMethod.POST})
    @ResponseBody
    public ResultMsg doSeckill(@PathVariable String code, HttpServletRequest request) throws IOException {
        Goods goods = goodsService.getGoodsByCode(code);
        User user = (User) request.getSession().getAttribute("session_user");

        //流量限制

        //库存检查
        ResultMsg stocks = stockService.checkStock(goods.getId());
        if(stocks.getCode() != 0) {
            return ResultUtil.error(100, "库存不够");
        }

        //扣减库存
        Long leftStock = stockService.dedStock(goods.getId(), -1);
        if(leftStock < 0) {
            return ResultUtil.error(100, "库存不够");
        }

        //编码
//        OrderMessage message = new OrderMessage();
//        message.userId  = user.getId();
//        message.num     = 1;
//        message.goodsId = goods.getId();
//        message.timestamp = (int)(System.currentTimeMillis() / 1000);
//
//        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//        ObjectOutputStream oos = new ObjectOutputStream( baos );
//        oos.writeObject( message );
//        String msg =  Base64.getEncoder().encodeToString(baos.toByteArray());
//
//        //发送消息队列
//        rocketMQTemplate.convertAndSend("TopicTest",  msg);

        //
        int orderId = orderService.ordering(goods, user.getId());

        DefaultMQProducer producer = new DefaultMQProducer("orderProducer");
        try {
            //producer.setNamesrvAddr("127.0.0.1:9876");
            producer.start();
            Message msg = new Message("seckill_orders", Integer.toString(orderId).getBytes());
            msg.setDelayTimeLevel(4);
            producer.send(msg);
        } catch ( Exception e) {
            System.out.println(e.getMessage());
        }
        producer.shutdown();

        return ResultUtil.success(orderId);
    }

    @RequestMapping(value = "/pay/{id}", method = {RequestMethod.POST})
    @ResponseBody
    public ResultMsg pay(@PathVariable int id) {
        orderService.updateOrderPayStatus(id, 1);
        return ResultUtil.success();
    }

    @RequestMapping("/payresult/{result}")
    public ModelAndView result(@PathVariable String result) {
        ModelAndView modelAndView = new ModelAndView("result");
        if(result.equals("suc")) {
            modelAndView.addObject("result", "true");
        } else {
            modelAndView.addObject("result", "false");
        }

        return modelAndView;
    }
}
